import { Injectable } from '@nestjs/common';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { ArticleContentUserReviewEntity } from './article-content-user-review.entity';
import { ArticleContentUserReviewDto } from './article-content-user-review.dto';
import { UserEntity } from '~/modules/user/user.entity';
import { UserWechatEntity } from '~/modules/user/user-wechat/user-wechat.entity';
import { ArticleContentEntity } from '../article-content.entity';

@Injectable()
export class ArticleContentUserReviewService {
  constructor(
    @InjectRepository(ArticleContentUserReviewEntity)
    private readonly articleContentUserReviewRepository: Repository<ArticleContentUserReviewEntity>,
    @InjectDataSource()
    private readonly datasource: DataSource
  ) {}

  async save(userId: number, articleId: number, dto: ArticleContentUserReviewDto) {
    const existingReview = await this.articleContentUserReviewRepository.findOneBy({
      user: { id: userId },
      article: { id: articleId },
    });

    if (existingReview) {
      // 更新现有评论
      await this.articleContentUserReviewRepository.update(existingReview.id, {
        helpfulnessScore: dto?.helpfulnessScore ?? existingReview.helpfulnessScore,
        pushSatisfactionScore: dto?.pushSatisfactionScore ?? existingReview.pushSatisfactionScore,
        contentSatisfactionScore:
          dto?.contentSatisfactionScore ?? existingReview.contentSatisfactionScore,
      });
    } else {
      await this.articleContentUserReviewRepository.save({
        user: { id: userId },
        article: { id: articleId },
        ...dto,
      });
    }
  }

  async findOneByUserAndArticle(
    articleId: number,
    userId: number
  ): Promise<ArticleContentUserReviewEntity> {
    return await this.articleContentUserReviewRepository.findOne({
      where: {
        article: { id: articleId },
        user: { id: userId },
      },
    });
  }

  async getAllArticleReview(): Promise<Partial<ArticleContentUserReviewEntity>[]> {
    return await this.datasource
      .createQueryBuilder()
      .addSelect('article_review.created_at', 'createdAt')
      .addSelect('article_review.helpfulness_score', 'helpfulnessScore')
      .addSelect('article_review.push_satisfaction_score', 'pushSatisfactionScore')
      .addSelect('article_review.content_satisfaction_score', 'contentSatisfactionScore')
      .addSelect('userWechat.nickname', 'nickname')
      .addSelect('userWechat.phone', 'phone')
      .addSelect('articleContent.code', 'articleCode')
      .addSelect('articleContent.name', 'articleName')
      .from(ArticleContentUserReviewEntity, 'article_review')
      .leftJoin(UserEntity, 'user', 'user.id = article_review.user_id')
      .leftJoin(UserWechatEntity, 'userWechat', 'userWechat.id = user.wechat_id')
      .leftJoin(
        ArticleContentEntity,
        'articleContent',
        'articleContent.id = article_review.article_id'
      )
      .orderBy('article_review.id', 'DESC')
      .getRawMany();
  }
}
